package net.xdclass.config.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.time.LocalDateTime;

/**
 * @author Administrator
 * @description LocalDateTime 和 mysql中的datetime互相转换
 * @since 2023-08-19 15:22
 */
@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
    /**
     * 存入数据库调用
     * @param preparedStatement
     * @param i
     * @param localDateTime
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, LocalDateTime localDateTime, JdbcType jdbcType) throws SQLException {
        preparedStatement.setObject(i, Timestamp.valueOf(localDateTime));
    }

    /**
     * 从数据库中获取值调用
     * @param resultSet
     *          the rs
     * @param s
     *          Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
     * @return
     * @throws SQLException
     */
    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, String s) throws SQLException {

        Timestamp timestamp = resultSet.getTimestamp(s);
        return timestamp.toLocalDateTime();
    }

    /**
     * 从数据库中获取值调用
     * @param resultSet
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Timestamp timestamp = resultSet.getTimestamp(i);
        return timestamp.toLocalDateTime();
    }

    /**
     * 存储过程调用时，获取值
     * @param callableStatement
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public LocalDateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Timestamp timestamp = callableStatement.getTimestamp(i);
        return timestamp.toLocalDateTime();
    }
}
